using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Google.Protobuf;

namespace HuaXianQu.ProtoBuffEx.ToolEditor
{
    public class ProtoBuffAssembleEditor
    {
        private List<Type> messages { get; set; }
        private Assembly _assembly;

        ProtoDllTool protoDllTool = new ProtoDllTool();
        private Dictionary<string, Type> dict = new();

        private static Lazy<ProtoBuffAssembleEditor> value = new(GetProtoBuffAssembleEditor);

        public static bool GetProtoBuffStatic(string name, out IMessage message, out Type type)
        {
            return value.Value.GetProtoBuff(name, out message, out type);
        }

        public void Reset()
        {
            dict.Clear();
            _assembly = protoDllTool.GetProtoBuffAssembly();
            messages = _assembly.GetTypes().ToList().Where(t => typeof(IMessage).IsAssignableFrom(t)).ToList();
            foreach (var message in messages)
            {
                dict.Add(message.Name, message);
            }
        }

        public bool GetProtoBuff(string name, out IMessage message, out Type type)
        {
            if (dict.Count == 0)
            {
                Reset();
            }

            message = null;
            if (dict.TryGetValue(name, out type))
            {
                message = (IMessage)Activator.CreateInstance(type);
                return true;
            }

            return false;
        }

        public static ProtoBuffAssembleEditor GetProtoBuffAssembleEditor()
        {
            ProtoBuffAssembleEditor buffAssembleEditor = new ProtoBuffAssembleEditor();
            buffAssembleEditor.Reset();
            return buffAssembleEditor;
        }

        public static void Distory()
        {
            value = new Lazy<ProtoBuffAssembleEditor>(GetProtoBuffAssembleEditor);
        }
    }
}